package com.wsoft.utils.job;

import com.google.common.collect.Lists;
import com.wsoft.config.JobAutoConfiguration;
import com.wsoft.entity.TsJobEntity;
import com.wsoft.enums.JobStatusEnum;
import com.wsoft.handler.JobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * job 执行端管理
 * @Author z001
 * @Date 2024/10/23 13:20
 */
@ConditionalOnBean(JobAutoConfiguration.class)
@Slf4j
@Service
public class JobClientManager {

    private final JobLauncher jobLauncher;

    private final JobRepository jobRepository;

    private final List<JobHandler> jobInterfaceList;


    public JobClientManager(JobLauncher jobLauncher, JobRepository jobRepository,
                            List<JobHandler> jobInterfaceList) {
        this.jobLauncher = jobLauncher;
        this.jobRepository = jobRepository;
        this.jobInterfaceList = jobInterfaceList;
    }

    /**
     * 获取任务执行类
     *
     * @param jobClass
     * @return
     */
    private Optional<JobHandler> queryJobImpl(String jobClass) {
        return jobInterfaceList.stream().filter(e -> Objects.equals(e.getClassName(), jobClass)).findFirst();
    }

    /**
     * 更新任务
     * 1. 如果不存在则新增
     * 2. 如果存在则跟新状态
     * @param jobId
     */
    public void updateJob(TsJobEntity jobEntity) {
        if (null == jobEntity) {
            return;
        }
        if(JobStatusEnum.PAUSE.getType().equals(jobEntity.getStatus())){
            //修改为暂停,删除任务
            JobScheduler.removeJob(jobEntity.getId());
        }else if(JobStatusEnum.START.getType().equals(jobEntity.getStatus())){
            //启动任务
            jobLauncher.startOrRefreshJob(Lists.newArrayList(jobEntity));
        }
    }

    /**
     * 移除job
     * @param jobEntity
     */
    public void removeJob(TsJobEntity jobEntity) {
        if (null == jobEntity) {
            return;
        }
        JobScheduler.removeJob(jobEntity.getId());
    }

    /**
     * 立即执行任务
     *
     * @param msg
     */
    public boolean executeJob(TsJobEntity jobEntity) {
        if (null == jobEntity) {
            return false;
        }
        // 获取定时任务实现类
        Optional<JobHandler> optional = this.queryJobImpl(jobEntity.getClassPath());
        if (!optional.isPresent()) {
            return false;
        }

        // 通过执行器 执行任务
        jobEntity.setParams(jobEntity.getParams());
        JobExecutor jobExecutor = new JobExecutor(jobEntity, optional.get(),jobRepository);
        jobExecutor.execute();
        return true;
    }




}
